package com.s63.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.s63.entity.User;
import com.s63.service.IRoleService;
import com.s63.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    protected IUserService userService;
    @Autowired
    protected IRoleService roleService;

    @GetMapping
    public String getAll(User user,
                         @RequestParam(required = false, defaultValue = "1") Integer current,
                         @RequestParam(required = false, defaultValue = "2") Integer size,
                         Model model) {
//        QueryWrapper queryWrapper = Wrappers.query()
//                .like(StringUtils.hasText(user.getAccount()), "account", user.getAccount())
//                .like(StringUtils.hasText(user.getRealName()), "real_name", user.getRealName());
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class)
                .like(StringUtils.hasText(user.getAccount()), User::getAccount, user.getAccount())
                .like(StringUtils.hasText(user.getRealName()), User::getRealName, user.getRealName());
        ;
        model.addAttribute("page", userService.page(Page.of(current, size), queryWrapper));
        model.addAttribute("scores", userService.getScores());
        return "user/index";
    }

    @GetMapping("/add")
    public String add() {
        return "user/add";
    }

    @GetMapping("/update")
    public String update(Integer id, Model model) {
        model.addAttribute("user", userService.getById(id));
        model.addAttribute("roleList", roleService.list());
        return "user/update";
    }
    @PostMapping("/update")
    public String update(User user) {
        userService.update(user);
        return "redirect:/users";
    }

    @GetMapping("/del")
    public String del(Integer id) {
        userService.removeById(id);
        return "redirect:/users";
    }

    @PostMapping
    public String add(User user) {
        userService.save(user);
        return "redirect:/users";
    }

    @GetMapping("/view")
    public String view(Integer id, Model model) {
        model.addAttribute("user", userService.getById(id));
        return "user/view";
    }

}
